package com.dongdongshop.controller;

import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.UserService;
import com.dongdongsop.data.AjaxResult;
import com.dongdongsop.em.ResultEnum;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
@RequestMapping("user")
public class UserController {

    @DubboReference
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    //跳转注册页面
    @RequestMapping("toRegister")
    public String toRegister(){
        return "register";
    }

    //注册
    @RequestMapping("register")
    @ResponseBody
    public AjaxResult register(TbUser user,String verification){
        try {
            String o = (String)redisTemplate.opsForValue().get(user.getPhone());
            if (!verification.equals(o)){
                return AjaxResult.R(ResultEnum.VERIFICATIONCODEISINCORRECT);
            }
            if (redisTemplate.hasKey(user.getPhone()) == null){
                return AjaxResult.R(ResultEnum.INVALIDVERIFICATIONCODE);
            }
            int i = userService.register(user);
            return AjaxResult.OK().setData(i);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }


    //根据手机号发送MQ
    @RequestMapping("getPhone")
    @ResponseBody
    public AjaxResult getPhone(String phone){
        try {
            userService.getPhone(phone);
            return AjaxResult.OK();
        }catch (Exception e){
            return AjaxResult.ERROR();
        }
    }

    //跳转登录
    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }

    //登录
    @RequestMapping("login")
    @ResponseBody
    public AjaxResult login(TbUser user){
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
            try {
                subject.login(token);
            }catch (UnknownAccountException uae){
                return AjaxResult.R(ResultEnum.LOGIN_ERROR);
            }catch (IncorrectCredentialsException ice){
                ice.printStackTrace();
                return AjaxResult.R(ResultEnum.LOGIN_ERROR);
            }
            return AjaxResult.OK();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }
}
